﻿//1.导入模块
const express = require('express');
//2.创建服务器
let app = express();
//3.托管静态资源
app.use(express.static('jiangApi'));
// 4.1  
//  重定向随机图片地址 
app.get('/jiangimg', (req, res) => {
  // 获取访问者ip并打印
  function getClientIp (req) {
    var ipAddress;
    var forwardedIpsStr = req.header('x-forwarded-for');
    if (forwardedIpsStr) {
      var forwardedIps = forwardedIpsStr.split(',');
      ipAddress = forwardedIps[0];
    }
    if (!ipAddress) {
      ipAddress = req.connection.remoteAddress;
    }
    return ipAddress;
  };
  // 打印ip
  console.log(getClientIp(req))
  let mm = Math.floor(Math.random() * (2060 - 1 + 1) + 1)
  // 重定向到随机图片
  res.redirect(`http://jiangapi.jx211.cn/jiang (${mm}).png`)

})
//  4.2  返回json格式的图片数据
app.get('/jiangimgs', (req, res) => {
  let mm = Math.floor(Math.random() * (2060 - 1 + 1) + 1)
  res.send({
    data: {
      code: 200,
      url: `http://jiangapi.jx211.cn/jiang (${mm}).png`,
      declare: '江训慎出品,必属精品'
    }
  })
})
//6.开启服务器

app.listen(4399, () => {

  console.log('开启成功!');

})